'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //所有app 请求都在这里
* @File: app_handler.py
* @Time: 2025/11/5
* @All Rights Reserve By Brtc
'''
import json
import uuid
from dataclasses import dataclass
from typing import  Generator

from flask_login import login_required
from injector import inject
from langchain_openai import ChatOpenAI
from redis import Redis

from internal.core.agent.agents.agent_queue_manager import AgentQueueManager
from internal.core.agent.agents.function_call_agent import FunctionCallAgent
from internal.core.tools.builtin_tools.provider import BuiltinProviderManager
from internal.entity.agent_entity import AgentConfig
from internal.entity.conversation_entity import InvokeFrom
from internal.exception.exception import ValidateErrorException
from internal.schema.app_schema import CompletionReq
from internal.service import AppService, ApiToolService
from internal.task.demo_task import demo_task
from pkg.response.response import success_json, success_message, compact_generate_response


@inject
@dataclass
class AppHandler:
    redis_client:Redis
    app_service: AppService
    builtin_provider_manager:BuiltinProviderManager
    api_tool_service: ApiToolService

    def create_app(self):
        app = self.app_service.create_app()
        return success_message(f"创建应用成功, id 为{app.id}")

    def get_app(self, app_id:uuid.UUID):
        app = self.app_service.get_app(app_id)
        return success_message(f"获取app 成功名字是:{app.name}")

    def update_app(self, app_id:uuid.UUID):
        app = self.app_service.update_app(app_id)
        return success_message(f"更新app 成功 app 名字更新后是:{app.name}")

    def delete_app(self, app_id:uuid.UUID):
        app = self.app_service.delete_app(app_id)
        return success_message(f"应用删除成功id是:{app.id}")


    """
    * @Author Leon-liao
    * @Function:ping 行数
    * @Description //处理/ping 请求的函数 返回是一个 {ping:pong} json
    * @Date :2025/11/5  14:42
    * @Param:
    """
    def ping(self):
        """ping函数"""
        demo_task.delay(uuid.uuid4())
        return success_json("异步任务启动成功！")


    """
    * @Author Leon-liao
    * @Function:chat_bot 聊天函数
    * @Description //通过langchian 构建的第一个聊天机器人
    * @Date :2025/11/5  16:13
    * @Param:
    """
    @login_required
    def chat_bot(self):
        """聊天机器人接口"""
        req = CompletionReq()

        if not req.validate():
            raise ValidateErrorException(message="需要参数啊大哥")
        #2、定义工具列表
        tools = [
            self.builtin_provider_manager.get_tool("google", "google_serper")(),
            self.builtin_provider_manager.get_tool("gaode", "gaode_weather")(),
            self.builtin_provider_manager.get_tool("dalle", "dalle3")(),
        ]

        agent = FunctionCallAgent(
            AgentConfig(
                llm = ChatOpenAI(model="gpt-4o-mini"),
                enable_long_term_memory=True,
                tools = tools,
            ),
            AgentQueueManager(
                user_id = uuid.uuid4(),
                task_id=uuid.uuid4(),
                invoke_from=InvokeFrom.DEBUGGER,
                redis_client=self.redis_client
            )
        )


        def stream_event_response()->Generator:
            #流式时间输出响应
            for agent_queue_event in agent.run(req.query.data, [], "黄晓康是最牛逼的程序员"):
                data = {
                    "id":str(agent_queue_event.id),
                    "task_id":str(agent_queue_event.task_id),
                    "thought":agent_queue_event.thought,
                    "observation":agent_queue_event.observation,
                    "tool":agent_queue_event.tool,
                    "tool_input":agent_queue_event.tool_input,
                    "answer":agent_queue_event.answer,
                    "latency":agent_queue_event.latency,
                }
                yield f"event: {agent_queue_event.event.value}\ndata: {json.dumps(data)}\n\n"

        return compact_generate_response(stream_event_response())

